class User < ActiveRecord::Base
  
  validates :login, :presence => true

  #虚拟一个密码属性
  def password
    @password
  end

  def password=(pass)
    return unless pass
    @password = pass
    generate_password(pass)
  end

#验证密码正确的用户是否存在，存在则返回该用户，不存在false
 def self.authenticate(login, password)
    user = User.find_by_login(login)
    if user && Digest::SHA256.hexdigest(password + user.salt) == user.hashed_password
      return user
    end
    false
  end

private
#生成加密字符串
  def generate_password(pass)
  #生成一个10位随机盐，用于加密用
    salt = Array.new(10){rand(1024).to_s(36)}.join
    self.salt, self.hashed_password = 
      salt, Digest::SHA256.hexdigest(pass + salt)
  end
end